﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using CSGame.DispatcherService;
using Common;

namespace CSGame
{
	public partial class frmMain : Form
	{
		public ReceivedMessageHandler _receivedMessageHanlder;
		public ReceivedMessageHandler _userJoinedHandler;
		public ReceivedMessageHandler _userLeftHandler;
		public InvitedHandler _invitedHandler;
		public StartGame _startGame;

		string _userName;
		string _invitedUserName;
		DispatcherClient _dispatcher;

		bool _isPlaying;

		public frmMain()
		{
			InitializeComponent();
			CreateDelegates();
		}

		public frmMain(string userName, DispatcherClient dispatcher)
		{
			InitializeComponent();
			CreateDelegates();

			this._dispatcher = dispatcher;
			this._userName = userName;
		}

		private void CreateDelegates()
		{
			_isPlaying = false;

			_receivedMessageHanlder = new ReceivedMessageHandler(ReceiveMessage);
			_userJoinedHandler = new ReceivedMessageHandler(UserJoined);
			_userLeftHandler = new ReceivedMessageHandler(UserLeft);
			_invitedHandler = new InvitedHandler(Invited);
			_startGame = new StartGame(StartGame);
		}

		public DispatcherClient Dispatcher
		{
			get { return _dispatcher; }
			set { _dispatcher = value; }
		}

		public string UserName
		{
			get { return _userName; }
			set { _userName = value; }
		}

		private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
		{
			try
			{
				if (_dispatcher.State == System.ServiceModel.CommunicationState.Opened)
				{
					_dispatcher.Unsubscribe();
					_dispatcher.LeaveLobby(_userName);
					_dispatcher.Close();
				}
			}
			catch (Exception ex)
			{
			}
			finally
			{
				Application.Exit();
			}
		}

		private void txtChat_KeyDown(object sender, KeyEventArgs e)
		{
			e.Handled = true;
			e.SuppressKeyPress = true;
		}

		private void btnEnter_Click(object sender, EventArgs e)
		{
			try
			{
				string baseMsg = txtEnter.Text.Trim();
				if (baseMsg.Length > 0)
				{
					string msg = "\n[" + DateTime.Now.Hour.ToString() + ":" + DateTime.Now.Minute.ToString() +
						":" + DateTime.Now.Second.ToString() + "] " + _userName + " : " + baseMsg;
					_dispatcher.SendMessage(msg);
					txtEnter.Text = "";
				}
			}
			catch (Exception ex)
			{
				MessageBox.Show(Resources.AppClosing, Resources.ErrorMsgCaption);
				Application.Exit();
			}
		}

		private void frmMain_VisibleChanged(object sender, EventArgs e)
		{
			try
			{
				if (this.Visible)
				{

					_dispatcher.Subscribe();
					treeUsers.Nodes.Clear();
					string[] users = _dispatcher.GetAllUsers().Items;
					for (int i = 0; i < users.Length; i++)
					{
						treeUsers.Nodes.Add(users[i]);

					}
					_dispatcher.JoinLobby(_userName);
					this.Text = "[" + _userName + "]";
				}
				else
				{
					_dispatcher.Unsubscribe();
				}
			}
			catch (Exception ex)
			{
				MessageBox.Show(Resources.AppClosing, Resources.ErrorMsgCaption);
				Application.Exit();
			}
		}

		public void ReceiveMessage(string msg)
		{
			if (this.Visible)
				this.txtChat.AppendText(msg);
		}

		public void UserJoined(string userName)
		{
			treeUsers.Nodes.Add(userName);
		}

		public void UserLeft(string userName)
		{
			TreeNode node = null;
			foreach (TreeNode tn in treeUsers.Nodes)
			{
				if (tn.Text == userName)
				{
					node = tn;
					break;
				}
			}
			if (node != null)
				treeUsers.Nodes.Remove(node);
		}

		public void Invited(string userName, string invitedUserName)
		{
			try
			{
				if (_isPlaying)
					return;
				if (_userName == invitedUserName)
				{
					string msg = String.Format(Resources.InviteMsg, userName);
					if (MessageBox.Show(msg, Resources.InviteMsgCaption, MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
					{
						_dispatcher.CreateGame("", invitedUserName, userName);
					}
				}
			}
			catch (Exception ex)
			{
				MessageBox.Show(Resources.AppClosing, Resources.ErrorMsgCaption);
				Application.Exit();
			}
			
		}

		public void StartGame(GameInfo gameInfo)
		{
			if (_userName == gameInfo.PlayerName && gameInfo.GameAddress != "")
			{
				frmClient game = new frmClient(gameInfo);
				game.Show();
			}
		}

		private void treeUsers_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
		{
			if (e.Button == System.Windows.Forms.MouseButtons.Right)
			{
				ContextMenu menu = new ContextMenu();
				MenuItem menuInvite = new MenuItem(Resources.TreeContextMenuInvite);
				menu.MenuItems.Add(menuInvite);
				if (e.Node.Text == _userName)
				{
					menuInvite.Enabled = false;
				}
				menu.Show(treeUsers, new Point(e.X, e.Y));
				menuInvite.Click += new EventHandler(menuInvite_Click);
			}
		}

		void menuInvite_Click(object sender, EventArgs e)
		{
			try
			{
				MenuItem menuInvite = sender as MenuItem;
				_invitedUserName = treeUsers.SelectedNode.Text;
				_dispatcher.InviteToGame(_userName, _invitedUserName);
			}
			catch
			{
				MessageBox.Show(Resources.AppClosing, Resources.ErrorMsgCaption);
				Application.Exit();
			}
		}

		private void txtEnter_KeyDown(object sender, KeyEventArgs e)
		{
			if (e.KeyCode == Keys.Enter)
			{
				btnEnter_Click(this, new EventArgs());
			}
		}

		
	}
}
